package com.fadadianqi.logistics.admin.net.packet;

import com.fadadianqi.logistics.admin.net.Action;
import com.fadadianqi.logistics.admin.net.Packet;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class PacketParser {

    public static Packet parse(byte[] bytes) throws PacketParseException {
        try {
            return _parse(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new PacketParseException(e.toString());
        }
    }

    private static final Packet _parse(byte[] bytes) throws IOException {
        ByteArrayInputStream bas = new ByteArrayInputStream(bytes);
        DataInputStream dis = new DataInputStream(bas);
        int action = dis.readInt();
        int bodyLen = dis.readInt();
        Packet packet = null;
        byte[] bodyBytes = null;
        if (bodyLen > 0) {
            bodyBytes = new byte[bodyLen];
            int icnt = 0;
            int iAva = 0;
            while (icnt < bodyLen) {
                int ret = dis.read(bodyBytes, icnt, Math.min(bodyLen - icnt, iAva));
                icnt = icnt + ret;
                iAva = dis.available();
            }
            dis.close();
        }
        switch (action) {
            case Action.KEEP_ALIVE:
                packet = new KeepAlivePacket();
                break;
            case Action.KEEP_ALIVE_ACK:
                packet = new KeepAliveActPacket();
                break;
            case Action.SMS_PACKET:
                String json = new String(bodyBytes, Packet.CHARSET);
                packet = new SMSPacket(json);
                break;
            case Action.SMS_PACKET_ACK:
                packet = new SMSPacketAck(new String(bodyBytes, Packet.CHARSET));
                break;
            case Action.CLOSE_CONNECTION:
                packet = new CloseConnectionPacket();
                break;
            default:
                break;
        }
        return packet;
    }
}
